﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Model;
using System.Text.Json;
namespace Admin.NET.Application;

/// <summary>
/// 系统入库单表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class SysinstockorderService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Sysinstockorder> _sysinstockorderRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SysinstockorderService(SqlSugarRepository<Sysinstockorder> sysinstockorderRep, ISqlSugarClient sqlSugarClient)
    {
        _sysinstockorderRep = sysinstockorderRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询系统入库单表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询系统入库单表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SysinstockorderOutput>> Page(PageSysinstockorderInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _sysinstockorderRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Code.Contains(input.Keyword) || u.InType.Contains(input.Keyword) || u.WarehouseName.Contains(input.Keyword) || u.RelatedCode.Contains(input.Keyword) || u.GoodsName.Contains(input.Keyword) || u.AgentName.Contains(input.Keyword) || u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => u.Code.Contains(input.Code.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InType), u => u.InType.Contains(input.InType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarehouseName), u => u.WarehouseName.Contains(input.WarehouseName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.RelatedCode), u => u.RelatedCode.Contains(input.RelatedCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.GoodsName), u => u.GoodsName.Contains(input.GoodsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.AgentName), u => u.AgentName.Contains(input.AgentName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.DocumentStatus.HasValue, u => u.DocumentStatus == input.DocumentStatus.Value)
            .WhereIF(input.InDateRange?.Length == 2, u => u.InDate >= input.InDateRange[0] && u.InDate <= input.InDateRange[1])
            .WhereIF(input.InQuantity != null, u => u.InQuantity == input.InQuantity)
            .WhereIF(input.WarehouseAmount != null, u => u.WarehouseAmount == input.WarehouseAmount)
            .WhereIF(input.DeleteTimeRange?.Length == 2, u => u.DeleteTime >= input.DeleteTimeRange[0] && u.DeleteTime <= input.DeleteTimeRange[1])
            .Select<SysinstockorderOutput>();
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取系统入库单表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取系统入库单表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Sysinstockorder> Detail([FromQuery] QueryByIdSysinstockorderInput input)
    {
        return await _sysinstockorderRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加系统入库单表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加系统入库单表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost, UnitOfWork]
    public async Task<long> Add(AddSysinstockorderInput input)
    {
        Console.WriteLine($"===== 开始入库操作 =====");
        Console.WriteLine($"输入参数 - WarePlaceId: {input.WarePlaceId}, GoodsName: {input.GoodsName}, InQuantity: {input.InQuantity}");
        
        var entity = input.Adapt<Sysinstockorder>();
        Console.WriteLine($"Adapt后实体 - WarePlaceId: {entity.WarePlaceId}, GoodsName: {entity.GoodsName}");
        
        var result = await _sysinstockorderRep.InsertAsync(entity);
        Console.WriteLine($"插入结果: {result}, 实体ID: {entity.Id}");
        
        // 无论什么情况都尝试更新库位（如果没有库位ID会跳过）
        if (result)
        {
            Console.WriteLine("开始更新库位商品数据...");
            await UpdateWarePlaceGoods(entity);
        }
        else
        {
            Console.WriteLine("入库失败，跳过更新库位");
        }
        
        Console.WriteLine($"===== 入库操作完成，返回ID: {entity.Id} =====");
        return result ? entity.Id : 0;
    }
    
    /// <summary>
    /// 更新库位商品数据
    /// </summary>
    private async Task UpdateWarePlaceGoods(Sysinstockorder order)
    {
        try
        {
            Console.WriteLine($"[更新库位商品] 开始 - WarePlaceId: {order.WarePlaceId}, GoodsName: {order.GoodsName}");
            
            // 如果没有库位ID，跳过
            if (!order.WarePlaceId.HasValue)
            {
                Console.WriteLine("[更新库位商品] 缺少库位ID，跳过更新");
                return;
            }
            
            // 查找对应的库位
            var warePlace = await _sqlSugarClient.Queryable<WarePlaceModel>()
                .Where(x => x.Id == order.WarePlaceId.Value && !x.IsDelete)
                .FirstAsync();
            
            if (warePlace == null)
            {
                Console.WriteLine($"[更新库位商品] 库位不存在 - ID: {order.WarePlaceId.Value}");
                return;
            }
            
            Console.WriteLine($"[更新库位商品] 找到库位 - ID: {warePlace.Id}, Name: {warePlace.WarePlaceName}");
            Console.WriteLine($"[更新库位商品] ShopName内容长度: {warePlace.ShopName?.Length ?? 0}");
            
            // 创建或更新商品数据
            var goods = new WarePlaceGoods
            {
                GoodsId = order.Id,
                GoodsName = order.GoodsName ?? string.Empty,
                Quantity = order.InQuantity,
                Amount = order.WarehouseAmount,
                UnitPrice = order.InQuantity > 0 
                    ? order.WarehouseAmount / order.InQuantity 
                    : 0,
                OrderCode = order.Code,
                OrderDate = order.InDate,
                OperationType = 1, // 1: 入库
                UpdateTime = DateTime.Now
            };
            
            // 读取旧的商品列表（从JSON解析）
            List<WarePlaceGoods> goodsList = new List<WarePlaceGoods>();
            
            Console.WriteLine($"[更新库位商品] ShopName为空: {string.IsNullOrWhiteSpace(warePlace.ShopName)}");
            
            if (!string.IsNullOrWhiteSpace(warePlace.ShopName))
            {
                try
                {
                    var options = new JsonSerializerOptions
                    {
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                        PropertyNameCaseInsensitive = true,
                        AllowTrailingCommas = true
                    };
                    goodsList = JsonSerializer.Deserialize<List<WarePlaceGoods>>(warePlace.ShopName, options) ?? new List<WarePlaceGoods>();
                    Console.WriteLine($"[更新库位商品] 成功解析现有商品数量: {goodsList.Count}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[更新库位商品] 解析现有商品JSON失败: {ex.Message}");
                    goodsList = new List<WarePlaceGoods>();
                }
            }
            else
            {
                Console.WriteLine($"[更新库位商品] ShopName为空，将创建新商品列表");
            }
            
            // 检查是否已有该商品
            var existingGoods = goodsList.FirstOrDefault(g => g.GoodsName == order.GoodsName);
            
            if (existingGoods != null)
            {
                Console.WriteLine($"[更新库位商品] 找到现有商品: {existingGoods.GoodsName}, 当前数量: {existingGoods.Quantity}");
                // 累加数量和金额
                existingGoods.Quantity += goods.Quantity;
                existingGoods.Amount += goods.Amount;
                
                // 更新单价（总金额 / 总数量）
                if (existingGoods.Quantity > 0)
                {
                    existingGoods.UnitPrice = existingGoods.Amount / existingGoods.Quantity;
                }
                else
                {
                    existingGoods.UnitPrice = 0;
                }
                
                existingGoods.UpdateTime = DateTime.Now;
                Console.WriteLine($"[更新库位商品] 累加后 - 数量: {existingGoods.Quantity}, 金额: {existingGoods.Amount}, 单价: {existingGoods.UnitPrice}");
            }
            else
            {
                Console.WriteLine($"[更新库位商品] 未找到同名商品，添加新商品: {goods.GoodsName}, 数量: {goods.Quantity}");
                goodsList.Add(goods);
            }
            
            // 将整个列表序列化并保存
            var serializeOptions = new JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
                WriteIndented = false
            };
            var newShopName = JsonSerializer.Serialize(goodsList, serializeOptions);
            
            Console.WriteLine($"[更新库位商品] 准备保存 - 商品列表数量: {goodsList.Count}");
            Console.WriteLine($"[更新库位商品] 序列化后JSON长度: {newShopName.Length}");
            Console.WriteLine($"[更新库位商品] JSON内容前200字符: {newShopName.Substring(0, Math.Min(200, newShopName.Length))}");
            
            // 直接更新库位
            var updateResult = await _sqlSugarClient.Updateable<WarePlaceModel>()
                .SetColumns(it => new WarePlaceModel { ShopName = newShopName })
                .Where(it => it.Id == order.WarePlaceId.Value)
                .ExecuteCommandAsync();
            
            Console.WriteLine($"[更新库位商品] 保存完成！影响行数: {updateResult}, 库位ID: {order.WarePlaceId.Value}, 商品总数: {goodsList.Count}");
            Console.WriteLine($"[更新库位商品] 操作完成！");
        }
        catch (Exception ex)
        {
            // 记录错误但不影响入库操作
            Console.WriteLine($"更新库位商品数据失败: {ex.Message}");
            Console.WriteLine($"堆栈跟踪: {ex.StackTrace}");
        }
    }

    /// <summary>
    /// 更新系统入库单表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新系统入库单表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSysinstockorderInput input)
    {
        var entity = input.Adapt<Sysinstockorder>();
        await _sysinstockorderRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除系统入库单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除系统入库单表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSysinstockorderInput input)
    {
        var entity = await _sysinstockorderRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _sysinstockorderRep.FakeDeleteAsync(entity);   //假删除
        //await _sysinstockorderRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除系统入库单表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除系统入库单表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSysinstockorderInput> input)
    {
        var exp = Expressionable.Create<Sysinstockorder>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _sysinstockorderRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _sysinstockorderRep.FakeDeleteAsync(list);   //假删除
        //return await _sysinstockorderRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 导出系统入库单表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出系统入库单表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSysinstockorderInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSysinstockorderOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "系统入库单表导出记录");
    }
    
    /// <summary>
    /// 下载系统入库单表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载系统入库单表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSysinstockorderOutput>(), "系统入库单表导入模板");
    }
    
    private static readonly object _sysinstockorderImportLock = new object();
    /// <summary>
    /// 导入系统入库单表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入系统入库单表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (_sysinstockorderImportLock)
        {
            var stream = ExcelHelper.ImportData<ImportSysinstockorderInput, Sysinstockorder>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.DocumentStatus == null){
                            x.Error = "单据状态不能为空";
                            return false;
                        }
                        if (x.InQuantity == null){
                            x.Error = "入库数量不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Sysinstockorder>>();
                    
                    var storageable = _sysinstockorderRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Code), "入库单号不能为空")
                        .SplitError(it => it.Item.Code?.Length > 64, "入库单号长度不能超过64个字符")
                        .SplitError(it => it.Item.InType?.Length > 32, "入库类型长度不能超过32个字符")
                        .SplitError(it => it.Item.WarehouseName?.Length > 64, "仓库名称长度不能超过64个字符")
                        .SplitError(it => it.Item.RelatedCode?.Length > 64, "关联单号长度不能超过64个字符")
                        .SplitError(it => it.Item.GoodsName?.Length > 512, "入库货品长度不能超过512个字符")
                        .SplitError(it => it.Item.AgentName?.Length > 64, "经办人长度不能超过64个字符")
                        .SplitError(it => it.Item.Remark?.Length > 512, "备注长度不能超过512个字符")
                        .SplitInsert(_=> true) // 没有设置唯一键代表插入所有数据
                        .ToStorage();
                    
                    storageable.AsInsertable.ExecuteCommand();// 不存在插入
                    storageable.AsUpdateable.UpdateColumns(it => new
                    {
                        it.Code,
                        it.InType,
                        it.DocumentStatus,
                        it.InDate,
                        it.WarehouseName,
                        it.RelatedCode,
                        it.GoodsName,
                        it.AgentName,
                        it.InQuantity,
                        it.WarehouseAmount,
                        it.Remark,
                        it.DeleteTime,
                    }).ExecuteCommand();// 存在更新
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
